<template>
  <!-- 面包屑导航 -->
  <div className="break">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item style="font-size: 22px;padding: 15px 0 0 15px"><b>菜品</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <!-- 数据卡片 -->
  <div style="margin:20px">
    <el-row :gutter="20">
      <el-col :span="8" v-for="dish in dishes" :key="dish.did">
        <el-card style="margin-bottom: 20px">
          <div style="padding: 14px;">
            <h3>{{ dish.dname }}</h3>
            <el-image
                :style="{ width: '220px', height: '220px' }"
            :src="'http://localhost:8085' + dish.dphotourl"
            :alt="'菜品图片 - '+dish.dname"
            fit="cover"
            :preview-src-list="['http://localhost:8085' + dish.dphotourl]"
            >
            </el-image>
            <p style="color: brown"><b>价格: {{ dish.dprice }}元</b></p>
            <p style="color: black"><b>主要食材: {{ dish.dfood }}</b></p>
            <!-- 添加数量选择控件和加入购物车按钮 -->
            <div>
              <el-input-number v-model="dish.quantity" :min="1" @change="handleQuantityChange(dish)"></el-input-number>
              <el-button type="primary" @click="addToCart(dish)">加入购物车</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import request from '@/utils/canteen';
import { useRoute } from 'vue-router';
import { ElMessage, ElCard, ElRow, ElCol, ElButton, ElRate } from 'element-plus';
// 设置满分变量
const maxRating = ref(5);
const blogInfo = ref([])
// 使用 useRoute 钩子获取当前路由对象
const route = useRoute();
// 从查询参数中获取 mallid
const mallid = ref(route.query.mid);

const dishes = ref([]); // 用于存储菜品数据

onMounted(async () => {
  // 组件挂载时获取菜品数据
  if (mallid.value) {
    await fetchDishesByMallId(mallid.value);
  }
});

const fetchDishesByMallId = async (mallid) => {
  try {
    const response = await request({
      url: `/dishes/getall`,
      method: 'get',
      params: { mallid },
    });
    console.log(response.data); // 打印响应数据
    if (response.status === 200) {
      // 初始化每个菜品的数量为 1
      response.data.forEach(dish => dish.quantity = 1);
      dishes.value = response.data; // 更新数据
      console.log(dishes.value); // 打印更新后的数据
    } else {
      ElMessage.error('请求失败，状态码：' + response.status);
    }
  } catch (error) {
    ElMessage.error('请求失败：' + error.message);
  }
};

// 处理数量变化
const handleQuantityChange = (dish) => {
  console.log(`数量变更为: ${dish.quantity} 个`);
};

// 用于发送请求到后端的方法
const sendRequestToBackend = async (url, method, data) => {
  try {
    const response = await request({
      url,
      method,
      data,
    });
    return response;
  } catch (error) {
    ElMessage.error('请求失败：' + error.message);
  }
};

// 修改 addToCart 方法
const addToCart = async (dish) => {
  // 创建购物车项对象
  const cartItem = {
    did: dish.did,       // 菜品ID
    dname: dish.dname,    // 菜品名称
    price: dish.dprice,  // 菜品价格
    count: dish.quantity // 菜品数量
  };

  try {
    // 发送请求到后端添加商品到购物车
    const response = await sendRequestToBackend('/cart/add', 'post', cartItem);
    if (response.status === 200) {
      ElMessage({
        message: `已添加 ${dish.dname} x${dish.quantity} 到购物车，总价: ${dish.dprice * dish.quantity}`,
        type: 'success'
      });
      // 更新本地购物车数据
      cartItems.value.push(cartItem);
    } else {
      ElMessage.error('添加到购物车失败');
    }
  } catch (error) {
    ElMessage.error('添加到购物车失败：' + error.message);
  }
};
const cartItems = ref([]);


</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
.el-row :last-child {
  margin-bottom: 0;
}
.el-col {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  transition: 0.3s;
  height: 100%;
}
.el-card {
  box-shadow: none;
}
.el-button {
  margin-top: 10px;
  width: 100%; /* 按钮宽度为 100% */
}
</style>